package com.nice.rm.main;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.LinkedList;
import java.util.List;

import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.LongField;
import org.apache.lucene.document.StringField;
import org.apache.lucene.document.TextField;

import com.nice.rm.core.IndexObjConvertor;
import com.nice.rm.core.QueryParameter;
import com.nice.rm.core.RealTimeIndexManager;
import com.nice.rm.util.FileUtil;


public class App {

    public static void main(String[] args) throws Exception {
        String line = null;
        BufferedReader bread = new BufferedReader(new FileReader("./src/main/java/com/nice/rm/main/App.java"));
        RealTimeIndexManager manager = new RealTimeIndexManager("./index", 1024);
        MyStrConvertor myStrConvertor = new MyStrConvertor();
        while ((line = bread.readLine()) != null) {
            manager.processDoc(myStrConvertor.objToDoc(line), line);
        }
        bread.close();
        
        List<String> datas = new LinkedList<String>();
        int count = manager.query(new QueryParameter<String>(datas, 10, 0, "main", "detail", myStrConvertor));
        System.out.println("find:" + count);
        for (String beanTest : datas) {
            System.out.println(beanTest);
        }
        manager.close();
        Thread.sleep(3000);
        FileUtil.deleteFile(new File("./index"));
    }

    public static class MyStrConvertor implements IndexObjConvertor<String> {

        public String docToObj(Document doc) {
            return doc.get("detail");
        }

        public Document objToDoc(String bean) {
            Document doc = new Document();
            doc.add(new LongField("length", bean.length(), Field.Store.YES));
            doc.add(new TextField("detail", bean, Field.Store.YES));
            return doc;
        }

    }

    public static class MyConvertor implements IndexObjConvertor<BeanTest> {

        public BeanTest docToObj(Document doc) {
            BeanTest bean = new BeanTest();
            bean.setId(Long.valueOf(doc.get("id")));
            bean.setName(doc.get("name"));
            return bean;
        }

        public Document objToDoc(BeanTest bean) {
            Document doc = new Document();
            doc.add(new LongField("id", bean.getId(), Field.Store.YES));
            doc.add(new StringField("name", bean.getName(), Field.Store.YES));
            doc.add(new TextField("detail", bean.toString(), Field.Store.NO));
            return doc;
        }

    }
}
